# 操作Redis对话记录
import json

from credit_voice_service.dialogue.util.RedisHelper import redis_helper
from credit_voice_service.settings import log

SESSION_EXPIRE_SECONDS = 1800
LLM_RESULT_EXPIRE_SECONDS = 30


class dialogue_storage:
    def __init__(self):
        self.conn_redis = redis_helper
        self.SESSSIONPREFIX = "dialogueSession:"
        self.LLM_RESULT_PREFIX = "llmResult:"
        pass

    def get_dialogue_session(self, session_id, workspace_id):
        if session_id is None or workspace_id is None:
            return None
        session = None
        try:
            redisKey = self.get_redis_session_id(session_id, workspace_id)
            dialogueSession = self.conn_redis.get(redisKey)
            if dialogueSession is None:
                return None
            session = json.loads(dialogueSession)
        except Exception as e:
            log.error("[get_dialogue_session] get dialogue info Error: %s" % str(e))
        return session

    def set_dialogue_session(self, session_id, workspace_id, dialogue_session):
        redisKey = self.get_redis_session_id(session_id, workspace_id)
        self.conn_redis.setStringValueWithExpire(redisKey, json.dumps(dialogue_session, ensure_ascii=False),
                                                 SESSION_EXPIRE_SECONDS)

    def get_redis_session_id(self, session_id, workspace_id):
        return self.SESSSIONPREFIX + str(workspace_id) + ":" + session_id

    def get_dialogue_llm(self, session_id, workspace_id):
        if session_id is None or workspace_id is None:
            return None
        session = None
        try:
            redisKey = self.get_redis_llm(session_id, workspace_id)
            llm_result = self.conn_redis.get(redisKey)
            if llm_result is None:
                return None
            session = json.loads(llm_result)
        except Exception as e:
            log.error("[get_dialogue_llm] get dialogue llm result Error: %s" % str(e))
        return session

    def set_dialogue_llm(self, session_id, workspace_id, llm_result):
        redisKey = self.get_redis_llm(session_id, workspace_id)
        self.conn_redis.setStringValueWithExpire(redisKey, json.dumps(llm_result), LLM_RESULT_EXPIRE_SECONDS)

    def get_redis_llm(self, session_id, workspace_id):
        return self.LLM_RESULT_PREFIX + str(workspace_id) + ":" + session_id

    def mq_error_data(self, msg):
        self.conn_redis.setListRightPush("MQ_ERROR_DATA", json.dumps(msg, ensure_ascii=False))

    def mq_error_data_pop(self):
        return self.conn_redis.getListLeftPop("MQ_ERROR_DATA")


dialogueStorage = dialogue_storage()

if __name__ == '__main__':
    dialogue_storage = dialogue_storage()

    # dialogue_storage.get_dialogue_session('0-2199-665498914-1666618255712043008-1264', 55369)
    pass
